package CanvaWeb.CanvaWeb.Controller;

import CanvaWeb.CanvaWeb.Service.UserService;
import CanvaWeb.CanvaWeb.pojo.LoginResponse;
import CanvaWeb.CanvaWeb.pojo.UpdateUserRequest;
import CanvaWeb.CanvaWeb.pojo.UserRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import CanvaWeb.CanvaWeb.pojo.User;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    // 用户注册
    @PostMapping("/register")
    public ResponseEntity<Map<String, Object>> register(@RequestBody UserRequest userRequest) {
        Map<String, Object> response = new HashMap<>();
        try {
            String username = userRequest.getUsername();
            String password = userRequest.getPassword();
            String email = userRequest.getEmail();
            String phone = userRequest.getPhone();

            // 如果 role 没有传递，可以设置默认角色
            String role = userRequest.getRole() != null ? userRequest.getRole() : "USER";

            // 调用服务层方法注册用户
            User user = userService.registerUser(username, password, email, phone);

            if (user != null) {
                response.put("success", true);
                response.put("message", "注册成功: 用户名为 " + user.getUsername());
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "注册失败");
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
            }
        } catch (IllegalArgumentException e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "服务器内部错误：" + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    // 用户登录
    @PostMapping("/login")
    public ResponseEntity<LoginResponse> login(@RequestBody UserRequest userRequest, HttpSession session) {
        try {
            String username = userRequest.getUsername();
            String password = userRequest.getPassword();

            // 调用服务层方法验证用户
            User user = userService.loginUser(username, password);

            if (user == null) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(
                        new LoginResponse(
                                "error",
                                "用户名或密码错误",
                                null,
                                null
                        )
                );
            }

            // 登录成功，将 userId 存入 session
            session.setAttribute("userId", user.getId());

            // 登录成功，返回用户信息
            return ResponseEntity.ok(
                    new LoginResponse(
                            "success",
                            user.getUsername(), // 只返回用户名，避免重复描述
                            user.getId(),
                            user.getUsername()
                    )
            );

        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(
                    new LoginResponse(
                            "error",
                            "服务器内部错误：" + e.getMessage(),
                            null,
                            null
                    )
            );
        }
    }

    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getUser(@PathVariable Long id) {
        // 调用服务层获取用户
        User user = userService.getUserById(id);

        // 检查用户是否存在
        if (user != null) {
            // 构建响应 Map
            Map<String, Object> response = new HashMap<>();
            response.put("id", user.getId());
            response.put("username", user.getUsername());
            response.put("email", user.getEmail() != null ? user.getEmail() : ""); // 确保不返回 null
            response.put("phone", user.getPhone() != null ? user.getPhone() : ""); // 确保不返回 null
            response.put("score", user.getScore());

            // 返回成功响应
            return ResponseEntity.ok(response);
        } else {
            // 返回 404 响应
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "User not found");
            errorResponse.put("status", HttpStatus.NOT_FOUND.value());
            errorResponse.put("message", "No user found with ID " + id);

            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(errorResponse);
        }
    }



    @PostMapping("/{id}/update")
    public ResponseEntity<Map<String, Object>> updateUser(
            @PathVariable Long id,
            @RequestBody UpdateUserRequest updateUserRequest) {

        Map<String, Object> response = new HashMap<>();
        try {
            // 打印接收的数据
            System.out.println("UpdateUserRequest received - id: " + id + ", data: " + updateUserRequest);

            User updatedUser = userService.updateUser(
                    id,
                    updateUserRequest.getUsername(),
                    updateUserRequest.getPassword(),
                    updateUserRequest.getEmail(),
                    updateUserRequest.getPhone()
            );

            if (updatedUser == null) {
                response.put("success", false);
                response.put("message", "用户不存在或更新失败");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
            }

            response.put("success", true);
            response.put("message", "用户信息更新成功");
            response.put("user", updatedUser);
            return ResponseEntity.ok(response);
        } catch (IllegalArgumentException e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "服务器错误：" + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    @PutMapping("/score/{id}/{newScore}")
    public ResponseEntity<Map<String, Object>> updateUserScore(
            @PathVariable Long id,
            @PathVariable Integer newScore) {

        Map<String, Object> response = new HashMap<>();

        try {
            User updatedUser = userService.updateUserScore(id, newScore);

            response.put("success", true);
            response.put("message", "分数更新成功");
            response.put("user", updatedUser);
            return ResponseEntity.ok(response);

        } catch (IllegalArgumentException e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);

        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "服务器内部错误: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
}
